package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
	"net/http"
	"time"
)

var sysStat = stat{}

type stat struct {
	CPU float64 `json:"cpu"`
	RAM float64 `json:"ram"`
}

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func main() {
	go SetParams()
	engine := gin.Default()
	engine.Static("/stat", "./static")

	engine.GET("/api/getPer", gogogo)

	err := engine.Run(":8082")
	if err != nil {
		fmt.Println(err)
	}
}
func gogogo(c *gin.Context) {
	go getSysInfo(c)
}

func getSysInfo(c *gin.Context) {
	//升级get请求为webSocket协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer fmt.Println("ws连接关闭")
	defer ws.Close()
	for {
		//读取ws中的数据
		_, message, err := ws.ReadMessage()
		if err != nil {
			break
		}
		fmt.Println("收到的信息是:", message)
		//写入ws数据
		for true {
			marshal, _ := json.Marshal(sysStat)
			err = ws.WriteMessage(1, marshal)
			if err != nil {
				break
			}
			time.Sleep(time.Millisecond * 500)
		}
	}
}

func SetParams() {
	sysStat.RAM = GetMemPercent()
	sysStat.CPU = GetCpuPercent()
	time.Sleep(time.Millisecond * 500)
	SetParams()
}

func GetCpuPercent() float64 {
	percent, err := cpu.Percent(time.Millisecond*600, false)
	if err != nil {
		fmt.Println(err)
	}
	return percent[0]
}

func GetMemPercent() float64 {
	memInfo, err := mem.VirtualMemory()
	if err != nil {
		fmt.Println(err)
	}
	return memInfo.UsedPercent
}

//磁盘使用百分比
/*func GetDiskPercent() float64 {
	parts, _ := disk.Partitions(true)
	diskInfo, _ := disk.Usage(parts[0].Mountpoint)
	return diskInfo.UsedPercent
}*/
